package com.elight.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.elight.entity.Operator;
import com.elight.sys.service.PermissionService;
import com.elight.utils.OperatorProvider;

/**
 * 权限验证过滤器
 * @author zhoujunwen
 *
 */
@Component("authorizeCheckFilter")
public class AuthorizeCheckedInterceptor extends HandlerInterceptorAdapter {
	@Autowired
	private PermissionService service;
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			AuthorizeChecked authorizeChecked = ((HandlerMethod) handler).getMethodAnnotation(AuthorizeChecked.class);
			if(authorizeChecked == null)
				return true;
			if(authorizeChecked.ignore()) {
				return true;
			}
			Operator operator = OperatorProvider.getCurrent(request.getSession());
            if (operator == null)
            {
            	response.getWriter().print("<script>alert('对不起，Session已过期，请重新登录');</script>");
				return false;
            }
			String userId= operator.getUserId();
			String action = request.getRequestURI();
				boolean hasPermission = service.actionValidate(userId,action);
	            if (!hasPermission)
	            {
	            	response.getWriter().print("<script>alert('对不起，您没有权限访问当前页面。');</script>");
	                return false;
	            }
			return true;
		}
		return true;
	}
}
